package com.neusoft.bigdata.hbase.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.Set;

import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;

import com.neusoft.bigdata.hbase.ForPrepareData;

/**
 * 数据计算工具类，用于根据结果计算出所需要的值
 * 
 * @author lihzh
 * @date 2013-4-1 下午5:45:03
 */
public class DataCalculUtil {

	public static Map<String, Double> calAvg(Iterator<Result> resultIt) throws IOException {
		Map<String, Double> avgMap = new HashMap<String, Double>();
		if (!resultIt.hasNext()) {
			System.out.println("The iterator is empty.");
			return avgMap;
		}
		
		Map<String, Double> valueMap = new HashMap<String, Double>();
		int count = 0;
		while (resultIt.hasNext()) {
			Result result = resultIt.next();
			NavigableMap<byte[], byte[]> metricMap = result.getFamilyMap(Bytes
					.toBytes(ForPrepareData.COLUMN_FAMILY_NAME_METRICS));
			Set<Entry<byte[], byte[]>> entrySet = metricMap.entrySet();
			Iterator<Entry<byte[], byte[]>> entrySetIt = entrySet.iterator();
			while (entrySetIt.hasNext()) {
				Entry<byte[], byte[]> entry = entrySetIt.next();
				String metricName = new String(entry.getKey());
				double value = Double.valueOf(new String(entry.getValue()));
				Double oriValue = valueMap.get(metricName);
				valueMap.put(metricName, oriValue == null ? value : oriValue + value);
			}
			count++;
		}
		
		Iterator<Entry<String, Double>> entryIt = valueMap.entrySet()
				.iterator();
		while (entryIt.hasNext()) {
			Entry<String, Double> entry = entryIt.next();
			double avg = entry.getValue() / count;
			avgMap.put(entry.getKey(), avg);
		}
		return avgMap;

	}
}
